package com.example.design.clean_craftsmanship

/**
 *Create by Fanketly on 2022/9/2
 *Gitee:https://gitee.com/fanketly
 *desc: 第三章 TDD（Test-Driven Development） 可能是一种逐步递增式地为任意问题推演出算法的过程
 */
class IntSort {

    /**
     * 但是新手往往想不到这种解法，一方面是经验问题，一方面是受到之前写的测试的影响
     * 它较难解决，所以让我们尝试把之前写的测试删除重新写一个更容易通过的测试
     * */
    fun sort(list: MutableList<Int>): MutableList<Int> {    //快速排序
        if (list.size <= 1) return list
        val middle: Int = list[0]
        val largerList = list.filter { a -> a > middle }.toMutableList()
        val smallList = list.filter { a -> a < middle }.toMutableList()
        val equalList = list.filter { a -> a == middle }.toMutableList()
        val mutableList = mutableListOf<Int>()
//        递归
        mutableList.addAll(sort(smallList))
        mutableList.addAll(equalList)
        mutableList.addAll(sort(largerList))
//        if (list[0] > list[1]) {
//            middle = list[0]
//            list[0] = list[1]
//            list[1] = middle
//        }
        return mutableList
    }

}

class MyWrap {

    fun wrap(string: String): String {
        return string.replace(Regex("\\s+"), "\n")
    }

    private var mNum = 0
    private val mStringBuilder = StringBuilder()

    fun wrap(string: String, width: Int): String {
        if (width > string.length) return string
        val split = string.split(Regex("\\s+"))
        split.forEach {
            wrap2(it, width)
        }

        return mStringBuilder.toString()
    }

    //书里的示例代码，只处理1个空格
    fun wrap3(string: String, width: Int): String {

        return if (width >= string.length) {
            string
        } else {
            var br = string.lastIndexOf(" ", width)
            if (br == -1) br = width;
            string.substring(0, br).trim() + "\n" + wrap3(string.substring(br).trim(), width)
        }
    }

    //自己写的，字符串短时耗时差不多，字符串长时性能有优势，虽然没示例简洁，但是感觉更容易读懂
    private fun wrap2(it: String, width: Int) {
        mNum += it.length
        if (mNum == width) {
            mStringBuilder.append(it).append("\n")
            mNum = 0
        } else if (mNum < width) {
            mNum += 1
            mStringBuilder.append(it).append(" ")
        } else {
            if (it.length > width) {
                val i = width + it.length - mNum
                mStringBuilder.append(it.substring(0, i)).append("\n")
                mNum = 0
                wrap2(it.substring(i), width)
            } else {
                for (i in 0 until mNum - width) {
                    mStringBuilder.append(" ")
                }
                mStringBuilder.append("\n")
                mNum = 0
                wrap2(it, width)
            }
        }


    }
}